const { User } = require("../Config/sqliteDB");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const saltRounds = 12;
const accessTokenSecret = "abc123"; // 访问令牌密钥
const refreshTokenSecret = "123abc"; // 刷新令牌密钥（与访问令牌不同）
const accessTokenExpiry = "120m"; // 访问令牌有效期设为15分钟
const refreshTokenExpiry = "7d"; // 刷新令牌有效期设为7天
const db = require("../Config/database.js"); // 确保已引入数据库连接

// 获取所有用户
exports.getAllUsers = async (req, res) => {
  try {
    const sql = `SELECT id, username FROM user`;
    const [rows, fields] = await db.execute(sql);
    res.status(200).json({
      message: "成功获取用户列表",
      data: rows,
    });
  } catch (error) {
    console.error("获取用户列表失败:", error);
    res.status(500).json({ message: "服务器内部错误1" });
  }
};

// 注册用户
exports.registerUser = async (req, res) => {
  try {
    const { username, password, phone, avatarUrl } = req.body;
    const hashedPassword = await bcrypt.hash(password, saltRounds);
    const sql = `INSERT INTO user (username, password,phone,avatarUrl) VALUES (?, ?,?,?)`;
    await db.execute(sql, [username, hashedPassword, phone, avatarUrl]);
    res.status(201).json({ message: "用户注册成功" });
  } catch (error) {
    console.error("用户注册失败:", error);
    res.status(500).json({ message: "服务器内部错误2" });
  }
};

// 登录功能 - 生成双token
exports.loginUser = async (req, res) => {
  try {
    const { phone, password } = req.body;

    // 1. 根据用户名查询用户
    const sql = `SELECT id, phone, password FROM user WHERE phone = ?`;
    const [users] = await db.execute(sql, [phone]);

    if (users.length === 0) {
      return res.status(401).json({ message: "用户名或密码错误" });
    }

    const user = users[0];
    // 2. 验证密码
    const passwordMatch = await bcrypt.compare(password, user.password);

    if (!passwordMatch) {
      return res.status(401).json({ message: "用户名或密码错误" });
    }

    // 3. 生成访问令牌
    const accessToken = jwt.sign(
      { id: user.id, username: user.username },
      accessTokenSecret,
      { expiresIn: accessTokenExpiry }
    );

    // 4. 生成刷新令牌
    const refreshToken = jwt.sign({ id: user.id }, refreshTokenSecret, {
      expiresIn: refreshTokenExpiry,
    });

    // 5. 保存刷新令牌到数据库
    const saveTokenSql = `INSERT INTO refresh_tokens (user_id, token) VALUES (?, ?) ON DUPLICATE KEY UPDATE token = ?, created_at = CURRENT_TIMESTAMP`;
    await db.execute(saveTokenSql, [user.id, refreshToken, refreshToken]);

    // 6. 返回用户信息和两种令牌
    res.status(200).json({
      message: "登录成功",
      data: {
        id: user.id,
        username: user.username,
        accessToken: accessToken,
        refreshToken: refreshToken,
      },
    });
  } catch (error) {
    console.error("登录失败:", error);
    res.status(500).json({ message: "服务器内部错误3" });
  }
};

// 刷新访问令牌功能
exports.refreshAccessToken = async (req, res) => {
  try {
    const { refreshToken } = req.body;

    if (!refreshToken) {
      return res.status(401).json({ message: "未提供刷新令牌" });
    }

    // 验证刷新令牌
    let decoded;
    try {
      decoded = jwt.verify(refreshToken, refreshTokenSecret);
    } catch (error) {
      return res.status(401).json({ message: "无效的刷新令牌" });
    }

    // 验证刷新令牌是否在数据库中存在且有效
    const sql = `SELECT token FROM refresh_tokens WHERE user_id = ?`;
    const [tokens] = await db.execute(sql, [decoded.id]);

    if (tokens.length === 0 || tokens[0].token !== refreshToken) {
      return res.status(401).json({ message: "无效的刷新令牌" });
    }

    // 获取用户信息
    const userSql = `SELECT id, username FROM user WHERE id = ?`;
    const [users] = await db.execute(userSql, [decoded.id]);

    if (users.length === 0) {
      return res.status(401).json({ message: "用户不存在" });
    }

    const user = users[0];

    // 生成新的访问令牌
    const newAccessToken = jwt.sign(
      { id: user.id, username: user.username },
      accessTokenSecret,
      { expiresIn: accessTokenExpiry }
    );

    res.status(200).json({
      message: "访问令牌已刷新",
      accessToken: newAccessToken,
    });
  } catch (error) {
    console.error("刷新令牌失败:", error);
    res.status(500).json({ message: "服务器内部错误4" });
  }
};

// 注销功能
exports.logout = async (req, res) => {
  try {
    const userId = req.user.id; // 从验证后的token中获取用户ID

    // 从数据库中删除刷新令牌
    const sql = `DELETE FROM refresh_tokens WHERE user_id = ?`;
    await db.execute(sql, [userId]);

    res.status(200).json({ message: "成功注销" });
  } catch (error) {
    console.error("注销失败:", error);
    res.status(500).json({ message: "服务器内部错误5" });
  }
};
// 搜索好友
exports.searchFriends = async (req, res) => {
  try {
    const { keyword } = req.query;
    const sql = `SELECT id, username,avatarUrl FROM user WHERE username LIKE ?`;
    const [rows] = await db.execute(sql, [`%${keyword}%`]);
    res.status(200).json({
      message: "成功获取用户列表",
      data: rows,
    });
  } catch (error) {
    console.error("获取用户列表失败:", error);
    res.status(500).json({ message: "服务器内部错误6" });
  }
};

// 获取用户的好友列表
exports.getFriends = async (req, res) => {
  try {
    const userId = req.user.id;
    const sql = `
     SELECT DISTINCT u.id, u.username, u.avatarUrl, f.created_at as friend_since 
FROM friends f 
JOIN user u ON (f.friend_id = u.id AND f.user_id = ?) 
            OR (f.user_id = u.id AND f.friend_id = ?)
    `;
    const [rows] = await db.execute(sql, [userId, userId]);

    res.status(200).json({
      message: "成功获取好友列表",
      data: rows,
    });
  } catch (error) {
    console.error("获取好友列表失败:", error);
    res.status(500).json({ message: "服务器内部错误7" });
  }
};

// 发送好友请求
exports.sendFriendRequest = async (req, res) => {
  try {
    const senderId = req.user.id;
    const { receiverId } = req.body;

    // 检查是否是自己
    if (senderId === receiverId) {
      return res.status(400).json({ message: "不能添加自己为好友" });
    }

    // 检查是否已经是好友
    const checkFriendSql = `
      SELECT * FROM friends 
      WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)
    `;
    const [friendRows] = await db.execute(checkFriendSql, [
      senderId,
      receiverId,
      receiverId,
      senderId,
    ]);

    if (friendRows.length > 0) {
      return res.status(400).json({ message: "你们已经是好友了" });
    }

    // 检查是否已经发送过请求
    const checkRequestSql = `
      SELECT * FROM friend_requests 
      WHERE sender_id = ? AND receiver_id = ? AND status = 'pending'
    `;
    const [requestRows] = await db.execute(checkRequestSql, [
      senderId,
      receiverId,
    ]);

    if (requestRows.length > 0) {
      return res
        .status(400)
        .json({ message: "好友请求已发送，请等待对方回复" });
    }

    // 发送好友请求
    const sendRequestSql = `
      INSERT INTO friend_requests (sender_id, receiver_id, status) 
      VALUES (?, ?, 'pending')
      ON DUPLICATE KEY UPDATE status = 'pending', created_at = CURRENT_TIMESTAMP
    `;
    await db.execute(sendRequestSql, [senderId, receiverId]);

    // 添加实时通知逻辑
    const socketUtil = require("../utils/socketUtil");
    const senderInfo = await db.execute(
      `SELECT id, username, avatarUrl FROM user WHERE id = ?`,
      [senderId]
    );

    // 检查接收者是否在线，如果在线则发送实时通知
    if (socketUtil.isUserOnline(receiverId)) {
      socketUtil.sendToUser(receiverId, "new-friend-request", {
        id: Date.now(), // 临时ID
        sender_id: senderId,
        sender_name: senderInfo[0][0]?.username,
        sender_avatar: senderInfo[0][0]?.avatarUrl,
        created_at: new Date().toISOString(),
      });
    }

    res.status(201).json({ message: "好友请求已发送" });
  } catch (error) {
    console.error("发送好友请求失败:", error);
    res.status(500).json({ message: "服务器内部错误8" });
  }
};

// 获取好友请求列表
exports.getFriendRequests = async (req, res) => {
  try {
    const userId = req.user.id;
    const sql = `
      SELECT fr.id, fr.sender_id, u.username, u.avatarUrl, fr.created_at 
      FROM friend_requests fr 
      JOIN user u ON fr.sender_id = u.id 
      WHERE fr.receiver_id = ? AND fr.status = 'pending'
      ORDER BY fr.created_at DESC
    `;
    const [rows] = await db.execute(sql, [userId]);

    res.status(200).json({
      message: "成功获取好友请求列表",
      data: rows,
    });
  } catch (error) {
    console.error("获取好友请求列表失败:", error);
    res.status(500).json({ message: "服务器内部错误9" });
  }
};

// 处理好友请求
exports.handleFriendRequest = async (req, res) => {
  try {
    console.log("接收到好友请求处理");
    
    // 确保userId存在
    const userId = req.user?.id; // 使用可选链操作符安全获取
    const requestId = req.params?.requestId; // 从URL参数中获取requestId
    const { action } = req.body || {}; // 从请求体中获取action
    
    console.log("参数值: userId=", userId, "requestId=", requestId, "action=", action);
    
    // 参数验证 - 更严格的检查
    if (!userId || typeof userId !== 'number' && typeof userId !== 'string') {
      console.error("用户ID无效或未定义");
      return res.status(400).json({ message: "用户ID无效" });
    }
    
    // 转换为数值类型以确保类型安全
    const numericUserId = Number(userId);
    const numericRequestId = Number(requestId);
    
    if (isNaN(numericUserId) || isNaN(numericRequestId)) {
      console.error("用户ID或请求ID不是有效数字");
      return res.status(400).json({ message: "用户ID或请求ID无效" });
    }
    
    if (!action || !['accept', 'reject'].includes(action)) {
      console.error("操作类型无效");
      return res.status(400).json({ message: "操作类型无效" });
    }
    
    // 验证请求是否存在且属于当前用户
    const verifyRequestSql = `
      SELECT * FROM friend_requests 
      WHERE id = ? AND receiver_id = ? AND status = 'pending'
    `;
    console.log("执行SQL验证请求，参数:", numericRequestId, numericUserId);
    const [requestRows] = await db.execute(verifyRequestSql, [numericRequestId, numericUserId]);
    
    if (requestRows.length === 0) {
      console.error("无效的好友请求或该请求不属于当前用户");
      return res.status(404).json({ message: "无效的好友请求" });
    }
    
    const request = requestRows[0];
    
    if (action === "accept") {
      try {
        await db.query("START TRANSACTION");
        
        // 更新好友请求状态 - 这仍然使用execute是安全的
        const updateRequestSql = `
          UPDATE friend_requests 
          SET status = 'accepted', updated_at = CURRENT_TIMESTAMP 
          WHERE id = ?
        `;
        await db.execute(updateRequestSql, [numericRequestId]);
        
        // 添加好友关系（双向）- 这仍然使用execute是安全的
        const addFriendSql = `
          INSERT INTO friends (user_id, friend_id) 
          VALUES (?, ?), (?, ?)
        `;
        await db.execute(addFriendSql, [
          numericUserId,
          request.sender_id,
          request.sender_id,
          numericUserId,
        ]);
        
        await db.query("COMMIT");
        
        // 获取好友信息用于通知
        const [friendInfoRows] = await db.execute(
          'SELECT id, username, avatarUrl FROM user WHERE id = ?',
          [request.sender_id]
        );
        
        // 先返回成功响应
        res.status(200).json({ message: "已添加好友" });
        
        // 然后尝试发送WebSocket通知（在响应之后）
        try {
          const socketUtil = require("../utils/socketUtil");
          
          // 通知当前用户刷新好友列表
          socketUtil.notifyFriendshipUpdate(numericUserId, 'added', friendInfoRows[0]);
          
          // 通知对方用户刷新好友列表
          socketUtil.notifyFriendshipUpdate(request.sender_id, 'added', {
            id: numericUserId,
            username: req.user.username,
            avatarUrl: req.user.avatarUrl
          });
        } catch (socketError) {
          console.error("发送WebSocket通知失败:", socketError);
          // 注意：这里不再抛出错误，避免影响已经成功的操作
        }
      } catch (transactionError) {
        await db.query("ROLLBACK");
        console.error("事务执行失败:", transactionError);
        throw transactionError;
      }
    } else if (action === "reject") {
      // 拒绝好友请求
      const rejectRequestSql = `
        UPDATE friend_requests 
        SET status = 'rejected', updated_at = CURRENT_TIMESTAMP 
        WHERE id = ?
      `;
      await db.execute(rejectRequestSql, [numericRequestId]);
      
      res.status(200).json({ message: "已拒绝好友请求" });
    }
  } catch (error) {
    console.error("处理好友请求失败，详细错误:", error.message);
    console.error("错误堆栈:", error.stack);
    res.status(500).json({ message: "服务器内部错误10" });
  }
};

// 删除好友
exports.deleteFriend = async (req, res) => {
  try {
    const userId = req.user.id;
    const { friendId } = req.params;

    // 删除好友关系（双向）
    const deleteFriendSql = `
      DELETE FROM friends 
      WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)
    `;
    const [result] = await db.execute(deleteFriendSql, [
      userId,
      friendId,
      friendId,
      userId,
    ]);

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: "好友关系不存在" });
    }

    res.status(200).json({ message: "好友已删除" });
  } catch (error) {
    console.error("删除好友失败:", error);
    res.status(500).json({ message: "服务器内部错误11" });
  }
};
